package com.shikong.blog.security;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shikong.blog.common.Response;
import com.shikong.blog.service.CaptchaService;
import com.shikong.blog.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 验证码过滤器
 * @Version: 1.0
 */
/*CaptchaFilter用于验证码验证
 * 因为验证码值需要一次校验，所以继承OncePerRequestFilter
 * 自己写的过滤器要在security配置类中配置
 * */
@Slf4j
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String url = request.getRequestURI();
        //只有登陆时才会验证验证码
        if("/login".equals(url) && request.getMethod().equals("POST")){
            log.info("开始验证码验证");


            ObjectMapper mapper = new ObjectMapper();
            JsonNode jsonNode = mapper.readTree(request.getInputStream());
            System.out.println(jsonNode);
            String nonceStr = jsonNode.get("nonceStr").textValue();
            Integer captchaValue = jsonNode.get("captchaValue").intValue();
            String username = jsonNode.get("username").textValue();
            String password = jsonNode.get("password").textValue();
            // 查找匹配的key值，返回set集合
            stringRedisTemplate.opsForValue().set("username", username,5, TimeUnit.MINUTES);
            stringRedisTemplate.opsForValue().set("password", password,5, TimeUnit.MINUTES);

            String msg = captchaService.checkImageCode(nonceStr, captchaValue);
            if (StringUtils.isNotBlank(msg)) {
                ResultUtil.ok(response, Response.fail(msg));
            }
//            filterChain.doFilter(request,response);
        }
        //将请求转发给下一个过滤器
        filterChain.doFilter(request,response);
    }

}